

#import "QPNetWorkingTool.h"
#import <CommonCrypto/CommonCrypto.h>
#import "Reachability.h"


@implementation QPNetWorkingTool

+ (void)getNetWorkingTool:(NSString *)urlStr dic:(NSDictionary *)dic success:(SuccessBlock)success fail:(FailBlock)fail {
    if ([self checkTheNetWorking]) {
        // 有网
        AFHTTPSessionManager *man = [AFHTTPSessionManager manager];
        // 让AFN支持全部数据数据类型的解析
        [man.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
        // 调用AFN的get请求
//        [man GET:urlStr parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            success(responseObject);
//            [self data:responseObject urlStr:urlStr dic:dic type:0];
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            fail(error);
//        }];
        
        [man GET:urlStr parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            success(responseObject);
            [self data:responseObject urlStr:urlStr dic:dic type:0];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            fail(error);
        }];
        
    } else {
        // 走缓存
        id data = [self data:nil urlStr:urlStr dic:dic type:1];
        success(data);
    }
}

+ (void)postNetWorkingTool:(NSString *)urlStr dic:(NSDictionary *)dic success:(SuccessBlock)success fail:(FailBlock)fail {
    if ([self checkTheNetWorking]) {
        // 有网
        AFHTTPSessionManager *man = [AFHTTPSessionManager manager];
        // 让AFN支持全部数据数据类型的解析
        [man.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
//        [man POST:urlStr parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            // 返回数据
//            success(responseObject);
//            [self data:responseObject urlStr:urlStr dic:dic type:0];
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            fail(error);
//        }];
        
        [man POST:urlStr parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            // 返回数据
            success(responseObject);
            [self data:responseObject urlStr:urlStr dic:dic type:0];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            fail(error);
        }];
    } else {
        id data = [self data:nil urlStr:urlStr dic:dic type:1];
        success(data);
    }
}

// 利用MD5算法把网址转换成一串数字加字母
+ (NSString *)cachedFileNameForKey:(NSString *)key {
    const char *str = [key UTF8String];
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *fileName = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    return fileName;
}

// 获取或者存入数据
+ (id)data:(id)result urlStr:(NSString *)urlStr dic:(NSDictionary *)dic type:(NSInteger)type {// 0代表存, 1代表取
    // post特殊需要做个处理，因为post可能网址都相同，无法像get请求一样。所以这里把字典里的参数都拼接起来
    NSString *s = [NSString string];
    for (NSString *key in dic) {
        NSString *val = dic[key];
        s = [NSString stringWithFormat:@"%@%@", s, val];
    }
    // 获取真正的网址
    NSString *newStr = [NSString stringWithFormat:@"%@%@", urlStr, s];
    // 1. 获取文件名字
    NSString *fileName = [self cachedFileNameForKey:newStr];
    // 2. 找到cache文件夹所在的沙盒中的路径
    NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    // 3. 路径文件名拼接
    NSString *cachePath = [sandBoxPath stringByAppendingPathComponent:fileName];
    if (0 == type) {
        // 4. 把网络请求成功的数据归档
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:result];
        // 5. 写入本地
        [data writeToFile:cachePath atomically:YES];
        return nil;
    } else if (1 == type) {
        id data = [NSKeyedUnarchiver unarchiveObjectWithFile:cachePath];
        return data;
    } else {
        return nil;
    }
}

// 判断有无网络
+ (BOOL)checkTheNetWorking {
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    if (0 == reach.currentReachabilityStatus) {
        return NO;
    } else {
        return YES;
    }
}



@end
